package com.zhouyu.proxy;

import com.zhouyu.common.Invocation;
import com.zhouyu.common.URL;
import com.zhouyu.loadbalance.Loadbalance;
import com.zhouyu.protocol.HttpClient;
import com.zhouyu.register.MapRemoteRegister;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

public class ProxyFactory {
    public static  <T> T getProxy(Class interfaceClass){
        Object proxyInstance = Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                // 实现MOCK -Dmock=return:123456789
                String mock = System.getProperty("mock");
                if(mock!=null && mock.startsWith("return:")){
                    String result = mock.replace("return:","");
                    return result;
                }

                Invocation invocation = new Invocation(interfaceClass.getName(), method.getName(), method.getParameterTypes(), args);

                HttpClient httpClient = new HttpClient();

                // 服务发现
                List<URL> list = MapRemoteRegister.get(interfaceClass.getName());

                // 服务调用
                String result = null;
                List<URL> invokedUrls = new ArrayList<>();

                // 重试机制
                int max = 3;
                while (max > 0){
                    // 负载均衡
                    list.remove(invokedUrls);
                    URL url = Loadbalance.random(list);
                    invokedUrls.add(url);
                    try {
                        result = httpClient.send(url.getHostname(), url.getPort(), invocation);
                        return result;
                    }catch (Exception e){
                        if(max-- != 0) continue;
                        // error-callback=com.zhouyu.HelloServiceErrorCallback
                        // 容错
                        System.out.println("报错了");
                    }
                }

                return null;

            }
        });
        return (T) proxyInstance;
    }
}
